import json
import time

from sqlalchemy import select, update

from forward.api.admin.schemas.setting import (
    SettingNoticeListOutSchema,
    SettingNoticeDetailOutSchema,
    SettingNoticeSaveInSchema,
    SettingNoticeSchema,
)
from forward.dependencies.database import db
from forward.model.tables import NoticeSettingModel


class SettingNoticeService:
    """通知设置服务实现类"""

    engines = {
        "aliyun": {"name": "阿里云短信", "alias": "aliyun"},
        "tencent": {"name": "腾讯云短信", "alias": "tencent"},
    }

    async def list(self, recipient: int) -> list:
        """通知设置列表"""
        setting_records = await db.fetch_all(
            select(NoticeSettingModel)
            .where(
                NoticeSettingModel.recipient == recipient,
                NoticeSettingModel.is_delete == 0,
            )
            .order_by(NoticeSettingModel.id)
        )
        res = []
        settings = [
            SettingNoticeSchema.model_validate(i, from_attributes=True)
            for i in setting_records
        ]
        for s in settings:
            o = s.model_dump()
            if s.type == 1:
                o["type"] = "业务通知"
            else:
                o["type"] = "验证码"
            system_dict = json.loads(s.system_notice)
            sms_dict = json.loads(s.sms_notice)
            oa_dict = json.loads(s.oa_notice)
            mnp_dict = json.loads(s.mnp_notice)
            o["system_status"] = system_dict.get("status", 0)
            o["sms_status"] = sms_dict.get("status", 0)
            o["oa_status"] = oa_dict.get("status", 0)
            o["mnp_status"] = mnp_dict.get("status", 0)
            res.append(SettingNoticeListOutSchema(**o))
        return res

    async def detail(self, id_: int) -> SettingNoticeDetailOutSchema:
        """通知设置详情"""
        setting_record = await db.fetch_one(
            select(NoticeSettingModel).where(
                NoticeSettingModel.id == id_, NoticeSettingModel.is_delete == 0
            )
        )
        assert setting_record
        setting = SettingNoticeSchema.model_validate(
            setting_record, from_attributes=True
        )
        system_dict = json.loads(setting.system_notice)
        sms_dict = json.loads(setting.sms_notice)
        oa_dict = json.loads(setting.oa_notice)
        mnp_dict = json.loads(setting.mnp_notice)
        setting_dict = dict(setting)
        setting_dict["system_notice"] = system_dict
        setting_dict["sms_notice"] = sms_dict
        setting_dict["oa_notice"] = oa_dict
        setting_dict["mnp_notice"] = mnp_dict
        setting_dict["type"] = "业务通知" if setting_dict["type"] == 1 else "验证码"
        return SettingNoticeDetailOutSchema(**setting_dict)

    async def save(self, save_in: SettingNoticeSaveInSchema):
        """通知设置保存"""
        setting = await db.fetch_one(
            select(NoticeSettingModel).where(
                NoticeSettingModel.id == save_in.id, NoticeSettingModel.is_delete == 0
            )
        )
        assert setting
        save_dict = save_in.dict(exclude_none=True)
        save_dict["system_notice"] = json.dumps(
            save_dict["system_notice"], ensure_ascii=False
        )
        save_dict["sms_notice"] = json.dumps(
            save_dict["sms_notice"], ensure_ascii=False
        )
        save_dict["oa_notice"] = json.dumps(save_dict["oa_notice"], ensure_ascii=False)
        save_dict["mnp_notice"] = json.dumps(
            save_dict["mnp_notice"], ensure_ascii=False
        )
        await db.execute(
            update(NoticeSettingModel)
            .where(NoticeSettingModel.id == save_in.id)
            .values(**save_dict)
        )

    @classmethod
    async def instance(cls):
        """实例化"""
        return cls()
